//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include "gmutex.h"
#include <aura.h>

CGhostMutex::~CGhostMutex()
{
    if (NULL != m_hMutex) {
        AuraMutex_Destroy(m_hMutex);
        m_hMutex = NULL;
    }
}

ECode CGhostMutex::Initialize(
        /* [in]  */ WString name)
{
    assert(!name.IsNullOrEmpty());
    return (ECode)AuraMutex_Create((Aura_PWChar)(const wchar_t *)name, AURA_FALSE, &m_hMutex);
}

UInt32 CGhostMutex::AddRef(void)
{
    Int32 nRefs = m_nRefs.Increment();

    return (UInt32)nRefs;
}

UInt32 CGhostMutex::Release(void)
{
    Int32 nRefs = m_nRefs.Decrement();

    if (nRefs == 0) {
        GhostFactory factory(this->GetOid());
        Ghost::S_DeleteGhost(&factory, this);
        delete this;
    }
    return (UInt32)nRefs;
}

ECode CGhostMutexFactory::CreateGhost(
        /* [out] */ Ghost ** ppGhost,
        /* [out] */ Boolean * pbExisted)
{
    CGhostMutex * pGhost = NULL;
    ECode ec = NOERROR;

    assert(NULL != ppGhost);
    assert(NULL == pbExisted);

    pGhost = new CGhostMutex();
    if (NULL == pGhost) {
        ec = E_OUT_OF_MEMORY;
        goto ErrorExit;
    }
    ec = pGhost->Initialize(GetName());
    if (FAILED(ec)) {
        goto ErrorExit;
    }
    pGhost->AddRef();
    *ppGhost = pGhost;

    return ec;

ErrorExit:
    if (NULL != pGhost) {
        delete pGhost;
    }
    return ec;
}

